package com.jbit.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jbit.auth.JwtTokenUtil;
import com.jbit.common.ErrorCodeEnum;
import com.jbit.common.RespBean;
import com.jbit.common.ResultCode;
import com.jbit.common.condition.UserRegisterCondition;
import com.jbit.common.constans.SystemConstants;
import com.jbit.exception.BusinessException;
import com.jbit.exception.ServiceException;
import com.jbit.mapper.UserMapper;
import com.jbit.pojo.User;
import com.jbit.service.EmailService;
import com.jbit.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Value("${email.send.enable}")
    private boolean enableSendEmail;
    @Autowired
    private EmailService emailService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 用户注册
     *
     * @param condition
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean userRegister(UserRegisterCondition condition) {
        try {
            //先判断user_code是否存在
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getUserCode, condition.getUserCode());
            User user = this.baseMapper.selectOne(wrapper);
            if (!StringUtils.isEmpty(user)) {
                throw new BusinessException(ResultCode.USER_ACCOUNT_ALREADY_EXIST.getCode(), ResultCode.USER_ACCOUNT_ALREADY_EXIST.getMessage());
            }
            //如果不存在  就注册
            condition.setUserPassword(SecureUtil.md5(condition.getUserPassword()));
            User u = new User();
            BeanUtils.copyProperties(condition, u);
            u.setUserType(SystemConstants.UserType.REGISTRATION);
            this.save(u);//保存用户信息

            //生成激活码
            String activeCode = RandomUtil.randomNumbers(6);
            //发送邮件
            if (enableSendEmail) {
                emailService.sendTemplateEmail("1486315335@qq.com", "爱旅行注册验证码", activeCode);
            }
            //存入redis
            ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
            ops.set("active" + u.getUserCode(), activeCode, 30, TimeUnit.MINUTES);
        } catch (BeansException e) {
            throw new ServiceException(ErrorCodeEnum.SYSTEM_EXECUTION_ERROR);
        }
        return true;
    }

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @param request
     * @return
     */
    @Override
    public RespBean login(String username, String password, HttpServletRequest request) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return RespBean.error(ResultCode.PARAM_IS_BLANK);
        }
        User user = this.getOne(new LambdaQueryWrapper<User>().eq(User::getUserCode, username));
        if (user == null) {
            return RespBean.error(ResultCode.USER_ACCOUNT_NOT_EXIST);
        }
        //校验密码
        if (!user.getUserPassword().equals(SecureUtil.md5(password))) {
            return RespBean.error(ResultCode.USER_CREDENTIALS_ERROR);
        }
        //都通过之后 生成token
        String token = jwtTokenUtil.generatorToken(username);
        return RespBean.success().data("token", token);
    }
}

